const Router = require('koa-router');
const crypto = require('crypto');
const moment = require('moment');
const he = require('he');

const query = require('../lib/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const router = new Router();

router.prefix('/api/article');

module.exports = router;

/**
 * 获取所有文章
 */
router.get('/all', async (ctx, next) => {
  const { pageNo = 1, pageSize = 10 } = ctx.query;
  let list = await query(`
  select id,title,digest,cover,images,public_name,datetime
  from articles
  ORDER BY datetime DESC 
  limit ${+pageSize} offset ${(+pageNo - 1) * (+pageSize)}
  `);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  list = list.map(item => {
    item['images'] = item.images.split(',').filter(f => f) || [];
    item['datetime'] = moment(+`${item.datetime}000`).format('YYYY-MM-DD');
    return item;
  });

  ctx.body = await wrapper(list);
});

/**
 * 获取文章详情
 */
router.get('/detail', async (ctx, next) => {
  const { id } = ctx.query;
  if (!id) {
    ctx.body = await wrapper(new Error('缺少参数'));
    return false;
  }
  let list = await query(`
  select a.*,s.info,s.logo from articles a
  left join source s
  on a.public_num=s.num
  where a.id=${id}
  `);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  list[0].content = he.decode(list[0].content);
  list[0].images = list[0].images.split(',').filter(f => f) || [];
  list[0].datetime = moment(+`${list[0].datetime}000`).format('YYYY-MM-DD');

  ctx.body = await wrapper(list[0]);
});

/**
 * 关键字搜索
 * 支持多个关键词逗号连接
 */
router.get('/search', async (ctx, next) => {
  const { keywords } = ctx.query;

  if (!keywords) {
    ctx.body = await wrapper(new Error('请输入关键词.'));
    return false;
  }

  let list = await query(`
  select id,title,digest,cover,images,public_name,datetime
  from articles
  where title REGEXP "${keywords.replace(/,/img, '|')}"
  `);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  ctx.body = await wrapper(list);
});

/**
 * 获取公众号获取该公众号下所有文章
 */
router.get('/source', async (ctx, next) => {
  const { num = '', pageNo = 1, pageSize = 10 } = ctx.query;
  if (!num) {
    ctx.body = await wrapper(new Error('缺少参数'));
    return false;
  }
  let list = await query(`
  select a.id,a.title,a.digest,a.images,a.public_name,a.datetime,s.logo,s.info
  from source s
  left join articles a
  on a.public_num=s.num
  where s.num="${num}"
  ORDER BY datetime DESC 
  limit ${+pageSize} offset ${(+pageNo - 1) * (+pageSize)}
  `);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  list = list.map(item => {
    item['images'] = item.images.split(',').filter(f => f) || [];
    item['datetime'] = moment(+`${item.datetime}000`).format('YYYY-MM-DD');
    return item;
  });

  ctx.body = await wrapper(list);
});

/**
 * 获取收藏的所有文章
 */
router.get('/collection', async (ctx, next) => {
  const { ids = '' } = ctx.query;
  if (!ids) {
    ctx.body = await wrapper(new Error('缺少参数'));
    return false;
  }
  let list = await query(`
  select id,title,digest,cover,images,public_name,datetime
  from articles
  where id in (${ids})
  ORDER BY datetime DESC 
  `);

  if (checkError(list) || !Array.isArray(list)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  list = list.map(item => {
    item['images'] = item.images.split(',').filter(f => f) || [];
    item['datetime'] = moment(+`${item.datetime}000`).format('YYYY-MM-DD');
    return item;
  });

  ctx.body = await wrapper(list);
});
